using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.NoticeConfigs;
using Admin.NET.Core;
using MailKit.Net.Smtp;
using MimeKit;

namespace Admin.NET.Application;

public class EMailUtil
{
	/// <summary>
	/// 发送邮件并记录
	/// </summary>
	/// <param name="rep"></param>
	/// <param name="config"></param>
	/// <param name="toEmails"></param>
	/// <param name="subject"></param>
	/// <param name="body"></param>
	/// <param name="userId"></param>
	/// <returns></returns>
	public async Task SendEmailWithRecord(SqlSugarRepository<EmailRecord> rep, EmailConfig config, List<MailboxAddress> toEmails, string subject, string body, long userId)
	{
		EmailRecord record = new EmailRecord
		{
			Body = body,
			FromEmail = config.FromEmail,
			Subject = subject,
			TenantId = config.TenantId,
			CreateUserId = userId,
			ToEmails = toEmails.Select((MailboxAddress s) => s.Address).ToList()
		};
		string res = SendEmail(config, toEmails, subject, body);
		record.Result = res;
		await rep.InsertAsync(record);
	}

	/// <summary>
	/// 发送邮件
	/// </summary>
	/// <param name="config"></param>
	/// <param name="toEmails"></param>
	/// <param name="subject"></param>
	/// <param name="body"></param>
	/// <returns></returns>
	public string SendEmail(EmailConfig config, List<MailboxAddress> toEmails, string subject, string body)
	{
		MimeMessage message = new MimeMessage();
		message.From.Add(new MailboxAddress(config.Name, config.FromEmail));
		message.To.AddRange(toEmails);
		message.Subject = subject;
		message.Body = new TextPart("plain")
		{
			Text = body
		};
		string res = "";
		using (SmtpClient client = new SmtpClient())
		{
			client.Connect(config.Host, config.Port, config.EnableSsl);
			client.Authenticate(config.FromEmail, config.Password);
			res = client.Send(message);
			client.Disconnect(quit: true);
		}
		return res;
	}
}
